package com.bill.common.user.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.bill.common.business.dao.IBuyDAO;
import com.bill.common.business.entity.Buy;
import com.bill.common.system.dao.IRiFenHongDAO;
import com.bill.common.system.dao.ITransactionRecordDAO;
import com.bill.common.system.dto.RuleDTO;
import com.bill.common.system.dto.SingleGroupReportStatDTO;
import com.bill.common.system.dto.TransactionRecordDTO;
import com.bill.common.system.entity.TransactionRecord;
import com.bill.common.system.service.IRuleService;
import com.bill.common.system.service.ITransactionRecordService;
import com.bill.common.user.dao.IRegisterUserDAO;
import com.bill.common.user.dto.DaiShuJiangDTO;
import com.bill.common.user.dto.FuWuJiangDTO;
import com.bill.common.user.entity.RegisterUser;
import com.bill.common.utils.DoubleFormat;
import com.bill.common.utils.TranType;
import com.sinba.common.dto.PageDTO;

/**
 * 奖金
 * @author ADMIN
 *
 */
public class BonusService implements IBonusService {
	private static Logger logger = Logger.getLogger(BonusService.class);
	@Autowired
	private IRegisterUserService registerUserService;
	@Autowired
	private IRegisterUserDAO registerUserDAO;
	@Autowired
	private IRuleService ruleService;
	@Autowired
	private ITransactionRecordService transactionRecordService;
	@Autowired
	private ITransactionRecordDAO transactionRecordDAO;
	@Autowired
	private IRiFenHongDAO riFenHongDAO;
	@Autowired
	private IBuyDAO buyDAO;
	
	public String ADD = "ADD";
	public String CUT = "CUT";
	/**
	 * 日分红
	 * 日分红奖：（ 1%） （1.2%）（1.3%） （1.5%）   （2%）   （2.5%） （3.5%）   六星  七星 账户根据市场需求开放
	 * @return 分红结果
	 */
	@Transactional
	public synchronized String everyDayHong(int page , int rows){
		Long t1 = new Date().getTime();
		System.out.println("****************************日分红(发放)************************************");
		//读取分红值
		RuleDTO ruleDTO = ruleService.findRuleInfo();
		
		List<Buy> list = buyDAO.findFengHongData();
		
		
		int i=0;
		for(Buy buy:list){
			if(!tadayisfenghong(buy.getBuyUser(),"日利息("+buy.getId()+")")){
				TransactionRecord tr2 = new TransactionRecord();
				tr2.setLoginName(buy.getBuyUser());
				tr2.setTransactionObject("system");
				tr2.setTransactionType(TranType.RiFenHong);
				tr2.setRemark("日利息("+buy.getId()+")");
				transactionRecordService.updateTran(tr2, TranType.DYNAMIC, (buy.getBuyMoney()*ruleDTO.getYifenghong1()/100), TranType.ADD);
				
				buy.setFengHongDays(buy.getFengHongDays()+1);
				buyDAO.merge(buy);
				
				i++;
			}
			
		}
		
		
//		RegisterUserQueryDTO queryDto = new RegisterUserQueryDTO();
//		int start = ( page - 1 ) * rows;
//		queryDto.setStart( start );
//		queryDto.setLimit( rows );
//		queryDto.setStatus("Activation");
//		List<RegisterUser> regs = new ArrayList<RegisterUser>();
//		PageDTO pageDTO = registerUserDAO.findPager(queryDto, "asc", "registerUserId");
//		if(pageDTO.getData().size()>0){
//			regs = (List<RegisterUser>)pageDTO.getData();
//			//System.out.println("本次分红数量有："+pageDTO.getData().size());
//		}
//		//List<RegisterUser> regs = registerUserDAO.findActivationUser();
//		int i=0;
//		boolean isfafang = false;
//		List<RiFenHong> lists = new ArrayList<RiFenHong>();
//		for(RegisterUser reg : regs){
//			//冻结账号、L6级别 的账号不享受日分红
//			if(!"1".equals(reg.getUserStatus()) && !"L6".equals(reg.getRegisterLevel())){
//				TransactionRecord tr = null;
//				String loginName = reg.getLoginName();
//				// 耗时:107702
////				TransactionRecordDTO dto = new TransactionRecordDTO();
////				dto.setLoginName(loginName);
////				dto.setStart(0);
////				dto.setLimit(1);
////				dto.setTransactionType(TranType.RiFenHong);
////				PageDTO  pagedto = transactionRecordDAO.findTransactionRecordPager(dto, "desc", "recordId");
////				if(pagedto.getTotalSize()>0){
////					tr = (TransactionRecord)pagedto.getData().get(0);
////					if(isToday(tr.getOptDate())){
////						isfafang = true;
////					}else{
////						isfafang = false;
////					}
////				}
//				//判断是否出局
//				//boolean out = registerUserService.userOut(loginName);
//				boolean out =false;
//				boolean out1 = false;
//				//以下账号不享受分红
//				if("343688".equals(loginName) 
//						|| "470870".equals(loginName) 
//						|| "708001".equals(loginName) 
//						|| "022335".equals(loginName) 
//						|| "497439".equals(loginName)){
//					out1=true;
//				}
//				if(!tadayisfenghong(loginName) && !out && !out1){
//				//if(!isfafang && !out && !out1){
//					//投资级别
//					String registerLevel = reg.getRegisterLevel();
//					//投资金额
//					Long toujiLevel = RuleDTO.level.get(registerLevel);
//					
//					//判断当前用户封顶数
//					//查出我推荐数
////					Double top = 0D;
////					Integer recommerSum = registerUserService.userCount(loginName, "AllRecActivation", null);
////					if(recommerSum==0){
////						top = lvrule.get("L1Top")*toujiLevel;
////					}else if(recommerSum>=1 && recommerSum<5){
////						top = lvrule.get("L2Top")*toujiLevel;
////					}else if(recommerSum>=5 && recommerSum<10){
////						top = lvrule.get("L3Top")*toujiLevel;
////					}else if(recommerSum>=10 && recommerSum<15){
////						top = lvrule.get("L4Top")*toujiLevel;
////					}else if(recommerSum>=15){
////						top = lvrule.get("L5Top")*toujiLevel;
////					}
//					
//					//每日分红计算
//					Double award = ruleDTO.getYifenghong1()*toujiLevel/100;
//					
//					//所有日分红总计
//					Double allBonus = 0D;
//					if(tr!=null && tr.getSumOfMoney()!=null){
//						allBonus = tr.getSumOfMoney();
//					}else{
//						//出局：结合静态2倍（包括本金）出局此奖项不再享受。
//						allBonus = transactionRecordService.statTotalAward(loginName);
//						//System.out.println(loginName+">new allBonus:::"+allBonus);
//					}
//					if(allBonus==null){
//						allBonus = 0.0;
//					}
//					Double top = 0.0;
//
//					//子账户1.5倍出局
//					if("L7".equals(reg.getRegisterLevel())){
//						award = DoubleFormat.format(toujiLevel.doubleValue()/100);
//						top = RuleDTO.level.get(reg.getRegisterLevel())*1.5;
//					}else{
//						top = RuleDTO.level.get(reg.getRegisterLevel())*ruleDTO.getYifenghong2();
//					}
//					
//					if((allBonus+award)>top){//出局
//						System.out.println("出局:::"+reg.getLoginName()+","+allBonus+","+allBonus);
//						if(top<allBonus){
//							award = 0D;
//						}else{
//							award = top-allBonus;
//						}
//					}
//					if(award>0){
//						
////						RiFenHong riFenHong = new RiFenHong();
////						
////						riFenHong.setLoginName(loginName);
////						riFenHong.setUserId(reg.getRegisterMoney());
////						riFenHong.setRegisterMoney(reg.getRegisterMoney());
////						riFenHong.setFaFanMoeny(award);
////						riFenHong.setYiFaFanMoney(allBonus);
////						lists.add(riFenHong);
//						//得到全额
//						Double balance = transactionRecordService.findUserBalance(loginName, "Dynamic");
//						
//						TransactionRecord tr1 = new TransactionRecord();
//						tr1.setLoginName(loginName);
//						tr1.setTransactionObject("system");
//						tr1.setTransactionType(TranType.RiFenHong);
//						tr1.setSumOfMoney(allBonus+award);
//						tr1.setRemark("日分红");
//						
//						
//						tr1.setBalance(DoubleFormat.format(balance+award));
//						tr1.setIncome(DoubleFormat.format(award));
//						tr1.setOptDate(new Date());
//						tr1.setDtype("Dynamic");
//						transactionRecordDAO.save(tr1);
//						
//						//transactionRecordService.updateTran(tr1, "Dynamic", award, ADD);
//						
//					}
//					
//					i++;
//				}
//			}
//			
//		}
//		riFenHongDAO.mergeAll(lists);
		return "通道"+page+",耗时:"+(new Date().getTime()-t1)+"ms，本次成功分红数："+i;
	}
	
	@Transactional
	public String everyDayHong1(){
		Long t1 = new Date().getTime();
		return everyDayHong(0,10000);
	}
	
	private boolean tadayisfenghong(String loginName){
		return transactionRecordDAO.todayIsRecord(loginName, TranType.RiFenHong);
	}
	private boolean tadayisfenghong(String loginName,String team1){
		return transactionRecordDAO.todayIsRecord(loginName, TranType.StaticShiFang,team1);
	}
	
	/**
	 * 对碰奖
	 * @param ruleDTO 制度
	 * @param point 对碰点
	 * @param regUser 产生对碰会员
	 * @param acUser 激活会员
	 */
	@Transactional
	public void dpAward(RuleDTO ruleDTO , Long point , RegisterUser regUser,RegisterUser acUser){
		//找到我的接点
		if(StringUtils.hasText(regUser.getContactNo())){
//			System.out.println("point:::::::"+point);
			//接点人
			RegisterUser contactUser = registerUserDAO.findUniqueBy("loginName", regUser.getContactNo());
			//判断在接点人的左边还是右边，将对碰点累加
			if("aArea".equals(regUser.getRegisterLocation())){
				contactUser.setLeftPoint(contactUser.getLeftPoint()+point);
				contactUser.setLeftSum(contactUser.getLeftSum()+point);
			}else if("bArea".equals(regUser.getRegisterLocation())){
				contactUser.setRightPoint(contactUser.getRightPoint()+point);
				contactUser.setRightSum(contactUser.getRightSum()+point);
			}
			//计算对碰
			caleTouch(ruleDTO,contactUser,acUser);
			//计算完，再一个的接点计算
			dpAward(ruleDTO,point,contactUser,acUser);
		}
		
	}
	
	@Transactional
	private void caleTouch(RuleDTO ruleDTO  , RegisterUser contactUser , RegisterUser acuser){
		Long point = 0L ;
		//左区比右区大
		if(contactUser.getLeftPoint()>=contactUser.getRightPoint()){
			point = contactUser.getRightPoint();
			if(point>0){
				contactUser.setLeftPoint(contactUser.getLeftPoint()-point);
				contactUser.setRightPoint(0L);
			}
		}else{
			point = contactUser.getLeftPoint();
			if(point>0){
				contactUser.setRightPoint(contactUser.getRightPoint()-point);
				contactUser.setLeftPoint(0L);
			}
		}
		
		
		if(point>0 && contactUser.getActivationTime()!=null){
			Map<String , Double > rates = new HashMap<String, Double>();
			rates.put("L1", ruleDTO.getDuipeng1());
			rates.put("L2", ruleDTO.getDuipeng2());
			rates.put("L3", ruleDTO.getDuipeng3());
			rates.put("L4", ruleDTO.getDuipeng4());
			rates.put("L5", ruleDTO.getDuipeng5());
			rates.put("L6", ruleDTO.getDuipeng6());
			
			//对碰提升(0000=5,0001=6)
			String str = ruleDTO.getDuipeng13();
			Map<String, String> upMaps = new HashMap<String, String>();
			if(StringUtils.hasLength(str)){
				String[] strs = str.replace("，",",").split(",");
				for(String str1 : strs){
					if(StringUtils.hasLength(str1)){
						String[] str2 =  str1.split("=");
						upMaps.put(str2[0], str2[1]);
					}
				}
			}
			
			Double award = point.doubleValue()*(rates.get(contactUser.getRegisterLevel()))/100;

			
			//提升Map
			if(upMaps.get(contactUser.getLoginName())!=null){
				award = point.doubleValue()*Double.parseDouble(upMaps.get(contactUser.getLoginName()))/100;
				System.out.println("提升：：："+contactUser.getLoginName()+"--"+upMaps.get(contactUser.getLoginName()));
			}
			
			
//			以前的固定对碰率
//			Double award = DoubleFormat.format(point.doubleValue()*ruleDTO.getRule038()/100);
			//封顶
			Map<String , Double > tops = new HashMap<String, Double>();
			tops.put("L1", ruleDTO.getDuipeng7());
			tops.put("L2", ruleDTO.getDuipeng8());
			tops.put("L3", ruleDTO.getDuipeng9());
			tops.put("L4", ruleDTO.getDuipeng10());
			tops.put("L5", ruleDTO.getDuipeng11());
			tops.put("L6", ruleDTO.getDuipeng12());
//			tops.put("L7", ruleDTO.getDuipeng13()); 
			//Double top = tops.get(contactUser.getRegisterLevel());
			//日封顶为投资额自身的一半。
			Double top = contactUser.getRegisterMoney().doubleValue()/2;
			//我所有对碰奖
			TransactionRecordDTO dto = new TransactionRecordDTO();
			dto.setLoginName(contactUser.getLoginName());
			dto.setInOrExp("income");
			dto.setTransactionTypes(new String[]{TranType.DuiPengJiang});
			dto.setSearchType("todaySearch");
			List<SingleGroupReportStatDTO> sgrs =  transactionRecordService.statDtype(dto);
			Double allBonus = 0D;
			for(SingleGroupReportStatDTO sdto : sgrs){
				allBonus = allBonus + sdto.getAggField();
			}
//			之前系统吃了10%，所以统计的时候除以0.9
//			if(allBonus>0){
//				allBonus = allBonus/0.9;
//			}
//			System.out.println("allBonus:::"+allBonus);
			if((allBonus+award)>top){//出局
				System.out.println("出局:::"+contactUser.getLoginName()+","+allBonus+","+award);
				if(top<allBonus){
					award = 0D;
				}else{
					award = top-allBonus;
				}
			}
//			System.out.println("对碰奖:::"+award);
			if(award>0){
				//对碰奖
				TransactionRecord tr = new TransactionRecord();
				tr.setLoginName(contactUser.getLoginName());
				tr.setTransactionObject(acuser.getLoginName());
				tr.setTransactionType(TranType.DuiPengJiang);
				tr.setRemark("对碰奖，总奖金是："+DoubleFormat.format(award));
				transactionRecordService.updateTran(tr, "Dynamic", award, ADD);
				
				
//				TransactionRecord tr1 = new TransactionRecord();
//				tr1.setLoginName(contactUser.getLoginName());
//				tr1.setTransactionObject(acuser.getLoginName());
//				tr1.setTransactionType(TranType.DuiPengJiang);
//				tr1.setRemark("对碰奖，总奖金是："+DoubleFormat.format(award)+"，30%是："+DoubleFormat.format(award*0.3));
//				transactionRecordService.updateTran(tr1, "Static", award*0.3, ADD);
//				
//				
			}
		}
		
	}
	
	
	/**
	 * 代数奖
	 * @param activeUser 激活会员
	 * @param recommendUser 推荐会员
	 * @param dq 代数
	 * @param fuWuJiang 服务奖
	 */
	@Transactional
	public void algebraicAward(RuleDTO ruleDTO , RegisterUser activeUser,RegisterUser recommendUser,int dq,Double fuWuJiang,String fuwadezhu,List<DaiShuJiangDTO> dsjDtos){
		dq++;
		//比例
		Map<String , Double > bili = new HashMap<String, Double>();
		bili.put("L1", ruleDTO.getDaishu7());
		bili.put("L2", ruleDTO.getDaishu8());
		bili.put("L3", ruleDTO.getDaishu9());
		bili.put("L4", ruleDTO.getDaishu10());
		bili.put("L5", ruleDTO.getDaishu11());
		bili.put("L6", ruleDTO.getDaishu12());
		
		bili.put("L7", ruleDTO.getDaishu12());
		bili.put("L8", ruleDTO.getDaishu12());
		bili.put("L9", ruleDTO.getDaishu12());
		bili.put("L10", ruleDTO.getDaishu12());
		bili.put("L11", ruleDTO.getDaishu12());
		bili.put("L12", ruleDTO.getDaishu12());
		bili.put("L13", ruleDTO.getDaishu12());
		bili.put("L14", ruleDTO.getDaishu12());
		bili.put("L15", ruleDTO.getDaishu12());
		bili.put("L16", ruleDTO.getDaishu12());
		bili.put("L17", ruleDTO.getDaishu12());
		bili.put("L18", ruleDTO.getDaishu12());
		bili.put("L19", ruleDTO.getDaishu12());
		bili.put("L20", ruleDTO.getDaishu12());
		//奖金=服务奖  x 根据不能卡级别轩比例
		//System.out.println("bili.get(L+dq):"+bili.get("L"+dq)+",fuWuJiang:"+fuWuJiang);
		Double award = DoubleFormat.format(fuWuJiang*bili.get("L"+dq)/100);
		//System.out.println("award::::"+award);
		if(recommendUser.getActivationTime()!=null){
			
			//代
			Map<String , Double > chengs = new HashMap<String, Double>();
			chengs.put("L1", ruleDTO.getDaishu1());
			chengs.put("L2", ruleDTO.getDaishu2());
			chengs.put("L3", ruleDTO.getDaishu3());
			chengs.put("L4", ruleDTO.getDaishu4());
			chengs.put("L5", ruleDTO.getDaishu5());
			chengs.put("L6", ruleDTO.getDaishu6());
			
			//最大允许拿多少代
			int maxDq = chengs.get(recommendUser.getRegisterLevel()).intValue();

			if(dq<=maxDq){
				
//				DaiShuJiangDTO dsjDTO = new DaiShuJiangDTO();
//				dsjDTO.setRecommendUser(recommendUser);
//				dsjDTO.setFuwadezhu(fuwadezhu);
//				dsjDTO.setActiveUser(activeUser);
//				dsjDTO.setAward(award);
//				dsjDTO.setDq(dq);
//				dsjDtos.add(dsjDTO);
				TransactionRecord tr = new TransactionRecord();
				tr.setLoginName(recommendUser.getLoginName());
				tr.setTransactionObject(activeUser.getLoginName());
				tr.setTransactionType(TranType.DaiShuJiang);
				tr.setRemark("代数奖，总奖金是："+DoubleFormat.format(award));
				transactionRecordService.updateTran(tr, "Dynamic", award, ADD);
				
			}
		}
		
		if(dq <4 && recommendUser!=null && StringUtils.hasText(recommendUser.getRecommendUser())){
			RegisterUser user = registerUserDAO.findUniqueBy("loginName", recommendUser.getRecommendUser());
			algebraicAward(ruleDTO ,activeUser,user,dq,fuWuJiang,fuwadezhu,dsjDtos);
		}
			
	}
	
	/**
	 * 根据代数来分的奖项
	 */
	@Transactional
	public void algebraicAward(RuleDTO ruleDTO,RegisterUser activeUser,RegisterUser recommendUser,Long money,int dq){
		dq++;
		//第一代不拿，第二代开始拿
		if(dq>1){
			Integer recommendQuantity = recommendUser.getRecommendQuantity();
			
			Double bili = 0D;
			
			//直推2名会员享受第二代代数奖为5%
			if(dq==2 && recommendQuantity>=2){
				bili = ruleDTO.getDaishu7();
			}
			//直推3名会员享受第三代代数奖为3%
			if(dq==3  && recommendQuantity>=3){
				bili = ruleDTO.getDaishu8();
			}
			if(dq>=4 && recommendQuantity>=5){
				bili = ruleDTO.getDaishu9();
			}
			
			Double award = DoubleFormat.format(RuleDTO.level.get(activeUser.getRegisterLevel())*bili/100);
			
			if(activeUser.getRegisterMoney()>recommendUser.getRegisterMoney()){//如果新会员等级比推荐人等级还要高，那么以推荐人等级来计算
				award = DoubleFormat.format(RuleDTO.level.get(recommendUser.getRegisterLevel())*bili/100);
			}
			
			
			if(recommendUser!=null && award>0){
				TransactionRecord tr2 = new TransactionRecord();
				tr2.setLoginName(recommendUser.getLoginName());
				tr2.setTransactionObject(activeUser.getLoginName());
				if(dq>=4){
					tr2.setTransactionType(TranType.TuanDuJiang);
					tr2.setRemark("团队奖:"+dq+"代");
				}else{
					tr2.setTransactionType(TranType.DaiShuJiang);
					tr2.setRemark("代数奖:"+dq+"代");
				}
				
				transactionRecordService.updateTran(tr2,TranType.OTHER1, award, TranType.ADD);
			}
		}
		if(recommendUser.getRecommendUser()!=null){
			RegisterUser rec = registerUserDAO.findUniqueBy("loginName", recommendUser.getRecommendUser());
			algebraicAward(ruleDTO,activeUser,rec,null,dq);
		}
	}
	
	
	public void algebraicAward(RuleDTO ruleDTO , RegisterUser activeUser){
		//查出所有拿到当前会员激活的服务奖得主
		TransactionRecordDTO qdto = new TransactionRecordDTO();
		qdto.setTransactionObject(activeUser.getLoginName());
		qdto.setTransactionType(TranType.FuWuJiang);
		qdto.setDtype("Dynamic");
		qdto.setStart(0);
		qdto.setLimit(100);
		PageDTO pdto = transactionRecordService.findTransactionRecordPager(qdto, null, null);
		//根据服务奖得主发放代数奖
		List<TransactionRecordDTO> trs = (List<TransactionRecordDTO>)pdto.getData();
		for(TransactionRecordDTO tr:trs){
			//查出服务奖会员
			RegisterUser fuwuUser = registerUserDAO.findUniqueBy("loginName", tr.getLoginName());
			if(fuwuUser!=null){
				RegisterUser daiShuUser = registerUserDAO.findUniqueBy("loginName", fuwuUser.getRecommendUser());
				if(daiShuUser!=null){
					//System.out.println("正在代数："+tr.getIncome()+","+tr.getLoginName()+","+daiShuUser.getLoginName());
					List<DaiShuJiangDTO> dsjDtos = new ArrayList<DaiShuJiangDTO>();
					algebraicAward(ruleDTO,activeUser,daiShuUser,0,DoubleFormat.format(tr.getIncome()/0.7),tr.getLoginName(),dsjDtos);
					for(DaiShuJiangDTO dto : dsjDtos){
						
						TransactionRecord tr0 = new TransactionRecord();
						tr0.setLoginName(dto.getRecommendUser().getLoginName());
						tr0.setTransactionObject(dto.getFuwadezhu());
						tr0.setTransactionType(TranType.DaiShuJiang);
						
						tr0.setRemark(dto.getDq()+"代,激活:"+dto.getActiveUser().getLoginName()+"，总奖金是："+DoubleFormat.format(dto.getAward())+"，70%是："+DoubleFormat.format(dto.getAward()*0.7));
						transactionRecordService.updateTran(tr0, "Dynamic", dto.getAward()*0.7, ADD);


						TransactionRecord tr1 = new TransactionRecord();
						tr1.setLoginName(dto.getRecommendUser().getLoginName());
						tr1.setTransactionObject(dto.getFuwadezhu());
						tr1.setTransactionType(TranType.DaiShuJiang);
						tr1.setRemark(dto.getDq()+"代,激活:"+dto.getActiveUser().getLoginName()+"，总奖金是："+DoubleFormat.format(dto.getAward())+"，30%是："+DoubleFormat.format(dto.getAward()*0.3));
						transactionRecordService.updateTran(tr1, "Static", dto.getAward()*0.3, ADD);
					}
				}
			}
			
			
		}
	}
	
	
	/**
	 * 领导奖
	 * @param ruleDTO 制度
	 * @param dpAward 对碰奖
	 * @param activeUser 激活会员
	 * @param recommendUser 推荐会员
	 */
	@Transactional
	public void leaderAward(RuleDTO ruleDTO ,Double dpAward , RegisterUser activeUser,RegisterUser recommendUser){
//		System.out.println("****************************领导奖************************************");
		if(recommendUser!=null){
			String registerLevel = recommendUser.getRegisterLevel();
			if("L5".equals(registerLevel) || "L6".equals(registerLevel) || "L7".equals(registerLevel)){
//				System.out.println("领导奖...............................");
				Map<String , Double > maps = new HashMap<String, Double>();
				maps.put("L1", ruleDTO.getRule066());
				maps.put("L2", ruleDTO.getRule067());
				maps.put("L3", ruleDTO.getRule068());
				maps.put("L4", ruleDTO.getRule069());
				maps.put("L5", ruleDTO.getRule070());
				maps.put("L6", ruleDTO.getRule071());
				maps.put("L7", ruleDTO.getRule072());
				Double gaward = DoubleFormat.format(dpAward*maps.get(registerLevel)/100);
				if(gaward>0){
					TransactionRecord tr2 = new TransactionRecord();
					tr2.setLoginName(recommendUser.getLoginName());
					tr2.setTransactionObject(activeUser.getLoginName());
					tr2.setTransactionType(TranType.LingDaoJiang);
					tr2.setRemark("");
					transactionRecordService.updateTran(tr2, "Dynamic", gaward*0.7, ADD);
					
					TransactionRecord tr3 = new TransactionRecord();
					tr3.setLoginName(recommendUser.getLoginName());
					tr3.setTransactionObject(activeUser.getLoginName());
					tr3.setTransactionType(TranType.LingDaoJiang);
					tr3.setRemark("");
					transactionRecordService.updateTran(tr3, "Static", gaward*0.2, ADD);
				}
			}
		}
	}
	
	
	/**
	 * 服务奖
	 * 服务奖（见点奖）：1%
	 * 普卡拿3层
	 * 银卡拿5层
	 * 金卡拿8层
	 * 白金卡拿11层
	 * 钻石卡拿15层
	 * 伯爵卡拿20层
	 */
	@Transactional
	public void fuWuAward(RuleDTO ruleDTO , RegisterUser activeUser,RegisterUser contactUser,int cheng,List<FuWuJiangDTO> fwjDtos){
		if(activeUser!=null && contactUser!=null){
			cheng++;
			//层
			Map<String , Double > chengs = new HashMap<String, Double>();
			chengs.put("L1", ruleDTO.getFuwu1());
			chengs.put("L2", ruleDTO.getFuwu2());
			chengs.put("L3", ruleDTO.getFuwu3());
			chengs.put("L4", ruleDTO.getFuwu4());
			chengs.put("L5", ruleDTO.getFuwu5());
			chengs.put("L6", ruleDTO.getFuwu6());
			
			//服务奖比例
			//Double fuWnBili = ruleDTO.getFuwu1();
			Map<String , Double > fuWnBilis = new HashMap<String, Double>();
			fuWnBilis.put("L1", ruleDTO.getFuwu7());
			fuWnBilis.put("L2", ruleDTO.getFuwu8());
			fuWnBilis.put("L3", ruleDTO.getFuwu9());
			fuWnBilis.put("L4", ruleDTO.getFuwu10());
			fuWnBilis.put("L5", ruleDTO.getFuwu11());
			fuWnBilis.put("L6", ruleDTO.getFuwu12());
			
			
			String userlevel = contactUser.getRegisterLevel();
			//判断当前会员是否可以拿到当前层数的资金
			if(chengs.get(userlevel)>=cheng){
				//奖金
				Double gaward = DoubleFormat.format(RuleDTO.level.get(activeUser.getRegisterLevel())*fuWnBilis.get(activeUser.getRegisterLevel())/100);
				
//				FuWuJiangDTO fwjDto = new FuWuJiangDTO();
//				fwjDto.setContactUser(contactUser);
//				fwjDto.setActiveUser(activeUser);
//				fwjDto.setGaward(gaward);
//				fwjDto.setCheng(cheng);
//				fwjDtos.add(fwjDto);
				TransactionRecord tr2 = new TransactionRecord();
				tr2.setLoginName(contactUser.getLoginName());
				tr2.setTransactionObject(activeUser.getLoginName());
				tr2.setTransactionType(TranType.FuWuJiang);
				tr2.setRemark("第"+cheng+"层服务奖"+"，总奖金是："+DoubleFormat.format(gaward));
				transactionRecordService.updateTran(tr2, "Dynamic", gaward, ADD);
//				
//				TransactionRecord tr3 = new TransactionRecord();
//				tr3.setLoginName(contactUser.getLoginName());
//				tr3.setTransactionObject(activeUser.getLoginName());
//				tr3.setTransactionType(TranType.FuWuJiang);
//				tr3.setRemark("第"+cheng+"层服务奖"+"，总奖金是："+DoubleFormat.format(gaward)+"，30%是："+DoubleFormat.format(gaward*0.3));
//				transactionRecordService.updateTran(tr3, "Static", gaward*0.3, ADD);
			}
			
			if(cheng<=20 && StringUtils.hasText(contactUser.getContactNo())){
				//System.out.println("服务奖："+contactUser.getContactNo()+",层:"+cheng);
				contactUser = registerUserDAO.findUniqueBy("loginName", contactUser.getContactNo());
				fuWuAward(ruleDTO , activeUser,contactUser,cheng,fwjDtos);
			}
			
			
			
		}
		

	}

	/**
	 * 直推奖
	 * @param loginName 注册人账号
	 * @param ruleDTO
	 */
	public void directPush(String loginName,RuleDTO ruleDTO) {
		
		RegisterUser regUser = registerUserDAO.findUniqueBy("loginName",loginName);
		String recommendLoginName = regUser.getRecommendUser();
		String registerLevel = regUser.getRegisterLevel();
		
		RegisterUser recommendUser = registerUserDAO.findUniqueBy("loginName",recommendLoginName);
		
		Double rate = ruleDTO.getZhitui1();
		if("L2".equals(recommendUser.getRegisterLevel())){
			rate = ruleDTO.getZhitui2();
		}else if("L3".equals(recommendUser.getRegisterLevel())){
			rate = ruleDTO.getZhitui3();
		}else if("L4".equals(recommendUser.getRegisterLevel())){
			rate = ruleDTO.getZhitui4();
		}else if("L5".equals(recommendUser.getRegisterLevel())){
			rate = ruleDTO.getZhitui5();
		}
		//确定金额
		Long money = regUser.getRegisterMoney();
		if(regUser.getRegisterMoney()>recommendUser.getRegisterMoney()){
			money = recommendUser.getRegisterMoney();
		}
		
		
		
		
		Double gaward = 0.0;
		//直推奖奖金
		gaward = money*rate/100;
		if(gaward >0){
			TransactionRecord tr = new TransactionRecord();
			tr.setLoginName(recommendLoginName);
			tr.setTransactionObject(loginName);
			tr.setTransactionType(TranType.ZhiTuiJiang);
			tr.setRemark(loginName+"激活"+"，总奖金是："+DoubleFormat.format(gaward));
			transactionRecordService.updateTran(tr, TranType.DYNAMIC, gaward, ADD);
		}
	}
	
	 /**
	  * 管理奖（激活奖，运营中心提成）
	  * @param regUser
	  * @param activeUser
	  * @param ruleDTO
	  */
	 @Transactional
	 public void activeUserAward(RegisterUser regUser ,RegisterUser activeUser,RuleDTO ruleDTO){
		 if(regUser!=null && activeUser!=null){
			 
			 Long money = (RuleDTO.level.get(regUser.getRegisterLevel()));
			 if(regUser.getRegisterMoney()>activeUser.getRegisterMoney()){//如果新会员比激活会员等级还高，那么以激活会员等级为准
				 money = (RuleDTO.level.get(activeUser.getRegisterLevel()));
			 }
			 Double gaward = money*ruleDTO.getRule073()/100;
			 TransactionRecord tr = new TransactionRecord();
			 tr.setLoginName(activeUser.getLoginName());
			 tr.setTransactionObject(regUser.getLoginName());
			 tr.setTransactionType(TranType.GuanLiJiang);
			 tr.setRemark(regUser.getLoginName()+"激活"+"，总奖金是："+DoubleFormat.format(gaward));
			 transactionRecordService.updateTran(tr, TranType.DYNAMIC, gaward, TranType.ADD);
		 }
		
	 }
	
	
	/**
	* 是否是今天
	*
	* @param date
	* @return
	*/
	public static boolean isToday(final Date date) {
	        return isTheDay(date, new Date());
	}
	/**
	* 是否是指定日期
	*
	* @param date
	* @param day
	* @return
	*/
	public static boolean isTheDay(final Date date, final Date day) {
	        return date.getTime() >= dayBegin(day).getTime()
	                        && date.getTime() <= dayEnd(day).getTime();
	}
	/**
	* 获取指定时间的那天 00:00:00.000 的时间
	*
	* @param date
	* @return
	*/
	public static Date dayBegin(final Date date) {
	        Calendar c = Calendar.getInstance();
	        c.setTime(date);
	        c.set(Calendar.HOUR_OF_DAY, 0);
	        c.set(Calendar.MINUTE, 0);
	        c.set(Calendar.SECOND, 0);
	        c.set(Calendar.MILLISECOND, 0);
	        return c.getTime();
	}
	/**
	* 获取指定时间的那天 23:59:59.999 的时间
	*
	* @param date
	* @return
	*/
	public static Date dayEnd(final Date date) {
	        Calendar c = Calendar.getInstance();
	        c.setTime(date);
	        c.set(Calendar.HOUR_OF_DAY, 23);
	        c.set(Calendar.MINUTE, 59);
	        c.set(Calendar.SECOND, 59);
	        c.set(Calendar.MILLISECOND, 999);
	        return c.getTime();
	}
	
	/**
	 * 账户释放
	 * 直推及管理奖账户：每到3000或3000元的倍数时释放一次到现金账户。(后台可控)
	 */
	@Transactional
	public void other1AccountFreed(){
		RuleDTO ruleDTO = ruleService.findRuleInfo();
		//直推及管理奖账户
		List<Object[]> freedOther1s = transactionRecordDAO.freedOther1(ruleDTO.getRule016().longValue());
		for(Object[] objs : freedOther1s){
			String loginName = "";
			Double incomes = 0D;
			if(objs!=null && objs[0]!=null && objs[1]!=null){
				loginName = (String)objs[0];
				incomes = (Double)objs[1];
				System.out.println("other1AccountFreed:正在释放:"+loginName+","+incomes);
			}
			incomes = DoubleFormat.format(incomes);
			if(StringUtils.hasText(loginName) && incomes>0){
				//释放到现金账户
				TransactionRecord tr = new TransactionRecord();
				tr.setLoginName(loginName);
				tr.setTransactionObject("System");
				tr.setTransactionType(TranType.Other1ShiFang);
				tr.setRemark("代数和团队奖金释放");
				transactionRecordService.updateTran(tr, TranType.DYNAMIC, incomes, TranType.ADD);
				
				
				//释放
				TransactionRecord tr1 = new TransactionRecord();
				tr1.setLoginName(loginName);
				tr1.setTransactionObject("System");
				tr1.setTransactionType(TranType.Other1ShiFang);
				tr1.setRemark("代数和团队奖金释放");
				transactionRecordService.updateTran(tr1, TranType.OTHER1, incomes, TranType.CUT);
			}
		}
	}
	
	/**
	 * 账户释放
	 * 代数及团队奖账户：每7天释放一次到现金账户。
	 */
	@Transactional
	public void other2AccountFreed(){
		RuleDTO ruleDTO = ruleService.findRuleInfo();
		//直推及管理奖账户
		try {
			List<Object[]> freedOther2s = transactionRecordDAO.freedOther2(ruleDTO.getRule016().longValue());
			// TODO: handle exception
			for(Object[] objs : freedOther2s){
				String loginName = "";
				Double incomes = 0D;
				if(objs!=null && objs[0]!=null && objs[1]!=null){
					loginName = (String)objs[0];
					incomes = (Double)objs[1];
					System.out.println("other2AccountFreed:正在释放:"+loginName+","+incomes);
				}
				incomes = DoubleFormat.format(incomes);
				if(StringUtils.hasText(loginName) && incomes>0){
					//释放到现金账户
					TransactionRecord tr = new TransactionRecord();
					tr.setLoginName(loginName);
					tr.setTransactionObject("System");
					tr.setTransactionType(TranType.Other2ShiFang);
					tr.setRemark("代数及团队奖账户释放");
					transactionRecordService.updateTran(tr, TranType.DYNAMIC, incomes, TranType.ADD);
					
					
					//释放
					TransactionRecord tr1 = new TransactionRecord();
					tr1.setLoginName(loginName);
					tr1.setTransactionObject("System");
					tr1.setTransactionType(TranType.Other2ShiFang);
					tr1.setRemark("代数及团队奖账户释放");
					transactionRecordService.updateTran(tr1, TranType.OTHER1, incomes, TranType.CUT);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			
		}
		
		
	}
	
	/**
	 * 注册账户释放
	 * 每天释放相应投资额和收益到现金账户
	 */
	@Transactional
	public void staticAccountFreed(){
		RuleDTO ruleDTO = ruleService.findRuleInfo();
		List<RegisterUser> lists = registerUserDAO.findFreedUser();
		for(RegisterUser registerUser : lists){
			if(registerUser.getIssued()>0 && !tadayisfenghong(registerUser.getLoginName(),"收益释放")){
				Long freedMoney = registerUser.getRegisterMoney()*ruleDTO.getYifenghong1().longValue()/100;
				registerUser.setIssued(registerUser.getIssued()-freedMoney);
				System.out.println("staticAccountFreed:正在释放:"+registerUser.getLoginName()+","+freedMoney);
				//释放到现金账户
				TransactionRecord tr = new TransactionRecord();
				tr.setLoginName(registerUser.getLoginName());
				tr.setTransactionObject("System");
				tr.setTransactionType(TranType.StaticShiFang);
				tr.setRemark("收益释放");
				transactionRecordService.updateTran(tr, TranType.DYNAMIC, freedMoney.doubleValue(), TranType.ADD);
				
				
				//释放
				TransactionRecord tr1 = new TransactionRecord();
				tr1.setLoginName(registerUser.getLoginName());
				tr1.setTransactionObject("System");
				tr1.setTransactionType(TranType.StaticShiFang);
				tr1.setRemark("收益释放");
				transactionRecordService.updateTran(tr1, TranType.STATIC, freedMoney.doubleValue(), TranType.CUT);
			}
		}
	}
	
	@Transactional
	public void accountFreed(){
		System.out.println(new Date()+"-----------------自动释放----------------");
		this.staticAccountFreed();
		this.other1AccountFreed();
		//this.other2AccountFreed();
		
	}
}
